<?php
declare (strict_types=1);

namespace app\mall\logic\product\admin;

use app\common\exception\LogicException;
use app\mall\model\product\admin\ProductSwiper as SwiperModel;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 后台商品轮播逻辑层
 */
class ProductSwiper extends SwiperModel
{

    /**
     * 删除swiper
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/11/29
     *
     * @param int   $productId
     * @param array $attachIds
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function delSwiperByAttachIds(int $productId, array $attachIds)
    {
        $this->where('product_id', $productId)->whereIn('attach_id', $attachIds)->select()->each(function ($i) {
            if(!$i->delete()) throw new LogicException('删除轮播图失败');
        });
    }

    /**
     * 新增swiper
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/11/29
     *
     * @param int   $productId
     * @param array $attachIds
     * @throws Exception
     */
    public function addSwipers(int $productId, array $attachIds)
    {
        $save = [];
        foreach ($attachIds as $attachId) {
            $save[] = ['product_id' => $productId, 'attach_id' => $attachId];
        }
        $re = $this->saveAll($save);
        if ($re->isEmpty()) throw new LogicException('新增失败');
    }
}
